import React, { FC, useState } from "react";
import {useRequest, useTitle} from "ahooks";
import {Button, Empty, message, Modal, Space, Spin, Table, Tag, Typography} from "antd";
import { useSearchParams } from "react-router-dom";
import styles from "./Common.module.scss";
import QuesCard from "../../components/QuesCard";
import {ExclamationCircleFilled} from "@ant-design/icons";
import Search from "../../components/Search";
import SearchList from "../../components/Search";
import useQuestionSearch from "../../hooks/useQuestionSearch";
import {deleteQuestionListService, UpdateQuestionService} from "../../services/question";
const {confirm} = Modal;
const Trash: FC = () => {
  useTitle("妖妖问卷 - 标星问卷");
  const [selectedRowKeys,setSelectedRowKeys] = useState< string[] >([]);
  const { Title } = Typography;
  const carClum = [
    {
      title: "标题",
      dataIndex: "name",
    },
    {
      title: "发布状态",
      dataIndex: "isPublished",
      render: (isPublished: boolean) => {
        return isPublished ? (
          <Tag color="#87d068">已发布</Tag>
        ) : (
          <Tag color="#f50">未发布</Tag>
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "time",
    },
    {
      title: "问卷数量",
      dataIndex: "cont",
    },
  ];

    const {data={},loading,error,refresh} = useQuestionSearch({isDeleted:true});
    const {list =[],total = 0} =data;



    //这里使用了refresh的方式，
    //这样的话，前端会重新去请求后端的数据，然后又全量的筛选出那些isdeled为true的数据
    //todo 这里能不能做一些优化？ 增量的删除数据呢，其他没发生变化的不需要动呢？
    //具体的实现方式是，通过使用一个数组来存储被选中行的 key 值。
    // 然后，在执行恢复删除操作时，根据这些 key 值找到对应的行数据并进行修改
    // 最后，使用 React 的 state 机制来更新列表组件的数据源，实现局部更新。

    //这里重复点击的解决方案是： 设置防抖，或者使用disable的禁用
    const {run:restoreDeleted,loading:restoreDeletedLoading} = useRequest(  async ()=>{
         // console.log(selectedRowKeys+"???");
          //数组异步遍历异步执行
          for await (const id of selectedRowKeys ) {
               await UpdateQuestionService(id, {isDeleted:false})
          }

    },{
        manual:true,
        debounceWait:500,//防抖500毫秒
        onSuccess(){
            message.success("成功恢复")
            refresh();
            setSelectedRowKeys([]);
        }
    })

    //批量删除的业务逻辑
    const {loading:deletedLoading,run:handlerDeleted} = useRequest(
       async ()=>{
           return    await deleteQuestionListService(selectedRowKeys);
        },{
            manual:true,
            onSuccess(){
                message.success("删除成功");
                refresh();
                setSelectedRowKeys([]);
            }
        }
    )


    function del(){
      confirm(
          {
              title:"确定彻底删除问卷?",
              okText:"确定",
              cancelText:"取消",
              content:"彻底删除",
              icon:<ExclamationCircleFilled/>,
              onOk:()=>{
                  handlerDeleted();
              }
          }
      )
  }

  const TableCume = <>
      <div style={{marginBottom:"12px"}}>
          <Space>
              <Button type={"primary"} disabled={selectedRowKeys.length === 0} onClick={restoreDeleted}>恢复</Button>
              <Button type={"primary"} danger disabled={selectedRowKeys.length === 0} onClick={del}>删除</Button>
          </Space>
      </div>
      <Table
          dataSource={list}
          columns={carClum}
          pagination={false}
          rowKey={q=>q._id}
          rowSelection={{
              type: "checkbox",
              onChange:(selectedRowKeys)=>{
                  setSelectedRowKeys(selectedRowKeys as string[]);
              }
          }}
      ></Table>
  </>

  return (
    <div>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={4}>回收站</Title>
        </div>
        <div className={styles.right}>
            {/*( 搜索框)+{JSON.stringify(selectedRowKeys)}*/}
            <SearchList></SearchList>
        </div>
      </div>
      <div className={styles.content}>
          {loading && (
              <div style={{textAlign:"center"}}>
                  <Spin/>
              </div>
          )}
        {!loading && list.length === 0 && <Empty description={"暂无数据"} />}
        {!loading && list.length > 0 && (
                 TableCume
        )}
      </div>
      <div className={styles.footer}>分页</div>
      <p>回收站</p>
    </div>
  );
};
export default Trash;
